
#import <stdio.h>
#import <string.h>
#import "point3.h"
#import "api.h"
#import "WidgetBrowser.h"

@implementation WidgetBrowser
;
static id browserID, matrixID, selfID;

- init
{
  [super init];
  matrix = [[Matrix alloc] init];
  return self;
}

- awakeFromNib
{
  browserID = browser;
  matrixID = matrix;
  selfID = self;
  valid = 0;
  return self;
}

- (BOOL)browser:sender columnIsValid:(int)column
{
  return valid;
}

- (int)browser:sender fillMatrix:theMatrix inColumn:(int)column
{
  id cell;
  int i, rows, cols;
  [matrix getNumRows:&rows numCols:&cols];

  [theMatrix renewRows:rows cols:1];
  for (i = 0; i < rows; i++) {
    cell = [theMatrix cellAt:i:0];
    [cell takeStringValueFrom:[matrix cellAt:i:0]];
    [cell setTag:i];
    [cell setLoaded:YES];
    [cell setLeaf:YES];
  }

  valid = 1;

  return rows;
} 

- update
{
  valid = 0;
  [browser validateVisibleColumns];
  return self;
}

void uiAddWidget(const char *name, int index) {
  [matrixID insertRowAt:index];
  uiSetWidgetName(name, index);
}

void uiSetSelectedWidget(int index) {
  [[browserID matrixInColumn:0] selectCellAt:index:0];
  [selfID update];
}

int uiGetSelectedWidget() {
  return [[browserID matrixInColumn:0] selectedRow];
}

void uiSetWidgetName(const char *name, int index) {
  id cell;

  cell = [matrixID cellAt:index:0];
  [cell setStringValue:name];
  [selfID update];
}

const char *uiGetWidgetName(int index) {
  return [[matrixID cellAt:index:0] stringValue];
}

int uiWidgetIndex(const char *name) {
  int i, cols, rows;

  [matrixID getNumRows:&rows numCols:&cols];
  for (i = 0; i < rows; i++) 
    if (!strcmp([[matrixID cellAt:i:0] stringValue], name)) return i;
  return -1;
}
  
void uiDeleteWidget(int index) {
  [matrixID removeRowAt:index andFree:YES];
  [matrixID sizeToCells];
  [selfID update];
}

@end
